/**
 * Copyright (C) 2010 Cloudfarming <info@cloudfarming.nl>
 *
 * Licensed under the Eclipse Public License - v 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package nl.cloudfarming.client.sensor.greenseeker;

import java.util.List;
import javax.persistence.Query;
import nl.cloudfarming.client.model.SensorDataFile;
import nl.cloudfarming.client.sensor.SensorService;

/**
 *
 * @author Gerben Feenstra
 */
public class GreenseekerServiceImpl extends SensorService implements GreenseekerService{

    @Override
    protected String getModuleName() {
        return GreenseekerModule.MODULE_NAME;
    }

    public void persist(List<GreenseekerSensorData> greenseekerSensorDataList){
        startTransaction();
        for (GreenseekerSensorData sensorData : greenseekerSensorDataList) {
            merge(sensorData);
        }
        commit();
    }

    @Override
    public void persist(GreenseekerSensorData sensorData) {
        startTransaction();
        mergeGreenseekerSensorData(sensorData);
        getEntityManager().getTransaction().commit();
    }

    private void mergeGreenseekerSensorData(GreenseekerSensorData toBeMerged) {
        if (toBeMerged.getId() == 0) {
            getEntityManager().persist(toBeMerged);
        } else {
            toBeMerged = getEntityManager().merge(toBeMerged);
        }
    }
 
    @Override
    public void delete(GreenseekerSensorData toBeRemoved) {
        getEntityManager().remove(toBeRemoved);
        getEntityManager().flush();
    }
    
    protected void removeSensorDataFile(SensorDataFile toBeRemoved) {
        getEntityManager().remove(toBeRemoved);
    }

    @Override
     public GreenseekerSensorData findGreenseekerSensorDataById(long id){
        startTransaction();
        return getEntityManager().find(GreenseekerSensorData.class, id);
    }

    @Override
     public List <GreenseekerSensorData> findAllGreenseekerSensorData(){
        startTransaction();
        Query query = this.getEntityManager().createQuery("select g from GreenseekerSensorData g");
        return query.getResultList();
    }

 
}
